/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package jwu2.indexserver;

import java.util.ArrayList;
import java.util.List;
import jwu2.core.Addon;
import jwu2.core.Site;
import jwu2.core.Sites;
import jwu2.addondb.AddonDB;
import jwu2.log.Logger;

/**
 *
 * @author Rolf
 */
public class IndexServerFetcherThread implements Runnable {
    private static final long SLEEP_PERIOD = 1000;
    
    private IndexServerFetcher fetcher;

    private Thread ourThread;
    
    public static void startIndexFetcherThreads() {
        for(Site s : Sites.singleton().getSites().values()) {
            System.out.println("Starting thread for site: "+s);
            new IndexServerFetcherThread(s).start();
        }
    }
    
    private IndexServerFetcherThread(Site s) {
        fetcher = new IndexServerFetcher(s);
    }

    public void start() {
        ourThread = new Thread(this);
        ourThread.start();
    }

    public void run() {
        List<Addon> fetchedAddons;
        
        while(true) {
            fetchedAddons = null;

            if( fetcher.shouldFetch() ) {

                Logger.logln("Fetching addons from ["+fetcher.getSite()+"]...");

                fetchedAddons = fetcher.fetchAddons();

                if( fetchedAddons != null ) {
                    //Do something to update new addons into database of addons
                    AddonDB.singleton().updateAddons(fetchedAddons, fetcher.getSite());
                }
            }
            try {
                Thread.sleep(SLEEP_PERIOD);
            }
            catch (InterruptedException ex) {
                Logger.logln("Exception while sleeping: "+ex);
            }
        }
    }
}
